from fastapi import APIRouter, HTTPException, Depends
import requests
from playhouse.shortcuts import model_to_dict
from pydantic import BaseModel

from auth_service.auths import verify_token
import config
from model.one_api import ModelInfo, UpdateModelInfo, headers, get_models

router = APIRouter(
    prefix="/rag/model",
    tags=["model management"],
    responses={404: {"description": "Not found"}}
)


@router.get("/get_models", summary="获取模型列表")
async def get_models_api(
        page: int = 0,
        current_user = Depends(verify_token)
):
    try:
        # 访问one api接口获取模型列表
        response = requests.get(config.model["backend_url"], params={"p": page}, headers=headers)
        if response.status_code == 200:
            response_json = response.json()
            _models = response_json["data"]
            return {"code": 200, "data": _models, "message": "获取模型列表成功"}
        else:
            raise HTTPException(detail=response.text, status_code=response.status_code)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取模型列表失败: {str(e)}")


@router.get("/get_llms", summary="获取llm列表")
async def get_llms_api(
        current_user = Depends(verify_token)
):
    try:
        res = get_models("llm")
        return res
    except Exception as e:
            raise HTTPException(status_code=500, detail=f"获取llm模型列表失败: {str(e)}")


@router.get("/get_embeddings", summary="获取embedding列表")
async def get_embeddings_api(
        current_user = Depends(verify_token)
):
    try:
        res = get_models("embed")
        return res
    except Exception as e:
            raise HTTPException(status_code=500, detail=f"获取embed模型列表失败: {str(e)}")


@router.get("/get_reranker", summary="获取重排模型列表")
async def get_reranker_api(
        current_user = Depends(verify_token)
):
    try:
        res = get_models("rerank")
        return res
    except Exception as e:
            raise HTTPException(status_code=500, detail=f"获取rerank模型列表失败: {str(e)}")



@router.post("/create", summary="创建模型")
async def create_model_api(
        body: ModelInfo,
        current_user = Depends(verify_token)
):
    try:
        # 访问one api接口创建模型
        response = requests.post(config.model["backend_url"], json=body.dict(), headers=headers)
        if response.status_code == 200:
            return {"code": 200, "message": "创建模型成功"}
        else:
            raise HTTPException(detail=response.text, status_code=response.status_code)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建模型失败: {str(e)}")

@router.put("/update", summary="更新模型")
async def update_model_api(
        body: UpdateModelInfo,
        current_user = Depends(verify_token)
):
    try:
        # 访问one api接口更新模型
        response = requests.put(config.model["backend_url"], json=body.dict(), headers=headers)
        if response.status_code == 200:
            return {"code": 200, "message": "更新模型成功"}
        else:
            raise HTTPException(detail=response.text, status_code=response.status_code)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新模型失败: {str(e)}")


class StopModel(BaseModel):
    id: int
    status: int

@router.put("/stop", summary="启停模型")
async def stop_model_api(
        body: StopModel,
        current_user = Depends(verify_token)
):
    try:
        # 访问one api接口更新模型
        response = requests.put(config.model["backend_url"], json={"id": body.id, "status": body.status}, headers=headers)
        if response.status_code == 200:
            return {"code": 200, "message": "更新模型成功"}
        else:
            raise HTTPException(detail=response.text, status_code=response.status_code)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新模型失败: {str(e)}")


@router.delete("/delete", summary="删除模型")
async def delete_model_api(
        id: int,
        current_user = Depends(verify_token)
):
    try:
        # 访问one api接口删除模型
        response = requests.delete(f"{config.model['backend_url']}/{id}", headers=headers)
        if response.status_code == 200:
            return {"code": 200, "message": "删除模型成功"}
        else:
            raise HTTPException(detail=response.text, status_code=response.status_code)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除模型失败: {str(e)}")